# Copyright (c) 2024, json_wang and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
import datetime


class CP_Expense(Document):
	def validate(self):
		invoices = []
		for trip in self.child_trip:
			if trip.invoice_no is not None:
				invoices.append(trip.invoice_no)
		for other in self.child_other:
			if other.invoice_no is not None:
				invoices.append(other.invoice_no)
		invoice_set = set(invoices)
		if len(invoice_set) < len(invoices):
			frappe.throw("发票号重复,不能保存!")

	def before_save(self):
		self.trip_total = 0
		self.trip_bill_count = 0
		for trip in self.child_trip:			
			self.trip_total += trip.total
			self.trip_bill_count += trip.bill_count
		self.taxi_total = 0
		self.taxi_bill_count = 0
		self.hotel_total = 0
		self.hotel_bill_count = 0
		self.subsidy_total = 0
		self.subsidy_day_count = 0
		self.other_total = 0
		self.other_bill_count = 0
		for other in self.child_other:
			if 	other.expense_type == "市内交通":
				self.taxi_total += other.total
				self.taxi_bill_count += other.bill_count
			elif 	other.expense_type == "住宿":
				self.hotel_total += other.total
				self.hotel_bill_count += other.bill_count
			elif 	other.expense_type == "补贴":
				self.subsidy_total += other.total
				self.subsidy_day_count += other.day_count
			else:
				self.other_total += other.total
				self.other_bill_count += other.bill_count
		self.bill_count = self.trip_bill_count+self.taxi_bill_count+self.hotel_bill_count+self.other_bill_count
		self.amount_total = self.trip_total+self.taxi_total+self.hotel_total+self.subsidy_total+self.other_total
			
	def on_submit(self):
		for trip in self.child_trip:
			if not trip.invoice_no and trip.invoice_type == "数电票":
				frappe.throw("发票类型为数电票时发票号码不能为空!")
				return
			if trip.invoice_no is not None:
				invoice = frappe.get_doc('CP_Invoice', trip.invoice_no)
				if invoice.is_use == 1:
					frappe.throw("发票号:"+trip.invoice_no+"已经被报销过,不允许重复报销!")
				else:
					invoice.is_use = 1
					invoice.link_order = self.name
					invoice.save(ignore_permissions=True, ignore_version=True)
		for other in self.child_other:
			if not other.invoice_no and other.invoice_type == "数电票":
				frappe.throw("发票类型为数电票时发票号码不能为空!")
				return
			if other.invoice_no is not None:
				invoice = frappe.get_doc('CP_Invoice', other.invoice_no)
				if invoice.is_use == 1:
					frappe.throw("发票号:"+trip.invoice_no+"已经被报销过,不允许重复报销!")
				else:
					invoice.is_use = 1
					invoice.link_order = self.name
					invoice.save(ignore_permissions=True, ignore_version=True)